package com.game.service;

import java.util.HashMap;
import java.util.Map;

import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.game.doctor.JVMCodeHotFix;
import com.game.doctor.XmlConfigHotFix;
import com.game.globalconst.BIOrder;
import com.game.globalconst.KeyPrefix;
import com.game.globalconst.OrderType;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author ZGame 利用redis的订阅和发布,充当消息总线
 * 
 */
@Service
@Slf4j
public class RedissionBusService {

	private Map<Integer, OrderType> OrderTypeMap = new HashMap<>();

	@Autowired
	private RedissonClient redissonClient;
	@Value("${xmldata.config}")
	private String xmldataConfig;// xml

	public void registOrderType() {
		OrderTypeMap.put(1, new XmlConfigHotFix(xmldataConfig));//热更配置表
		OrderTypeMap.put(2, new JVMCodeHotFix());//热更代码
	}

	public void start() {
		//注册类型
		registOrderType();
		// BI总线
		RTopic biTopic = redissonClient.getTopic(KeyPrefix.SYSTEM_BI);
		biTopic.addListener(String.class, new MessageListener<String>() {
			@Override
			public void onMessage(CharSequence channel, String bIOrderStr) {
				BIOrder bIOrderObj = JSONObject.parseObject(bIOrderStr, BIOrder.class);
				log.info("收到命令orderId:" + bIOrderObj.getOrderId());
				OrderType orderType = OrderTypeMap.get(bIOrderObj.getOrderId());
				if (orderType != null) {
					orderType.action(bIOrderObj);
				}
			}
		});
	}
}